package main

import (
	"flag"
	"fmt"
	"os"

	"service-hello/internal/infrastructure/conf"

	etcdr "github.com/go-kratos/kratos/contrib/registry/etcd/v2"
	"github.com/go-kratos/kratos/v2"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/transport/grpc"
	"github.com/go-kratos/kratos/v2/transport/http"
	clientv3 "go.etcd.io/etcd/client/v3"
)

var configFile string
var enableHTTP bool

func init() {
	flag.StringVar(&configFile, "config-file", "configs/config.yaml", "specify runtime config file")
	flag.BoolVar(&enableHTTP, "enable-http", false, "wether enable http server")
}

func newApp(logger log.Logger, cfg *conf.Bootstrap, hs *http.Server, gs *grpc.Server) *kratos.App {
	var server kratos.Option
	if enableHTTP {
		server = kratos.Server(hs, gs)
	} else {
		server = kratos.Server(gs)
	}

	ec, _ := clientv3.New(
		clientv3.Config{
			Endpoints: []string{cfg.Register},
		},
	)

	return kratos.New(
		kratos.Name(cfg.Name),
		kratos.Logger(logger),
		// 配置注册中心
		kratos.Registrar(
			etcdr.New(
				ec,
				etcdr.Namespace("/"+cfg.Namespace),
			),
		),
		server,
	)
}

func main() {
	flag.Parse()

	cfg, err := conf.Load(configFile)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	logger := log.With(log.DefaultLogger, "ts", log.DefaultTimestamp)

	app, closeFunc, err := initApp(
		logger,
		cfg,
	)
	if err != nil {
		panic(err)
	}
	defer closeFunc()

	if err := app.Run(); err != nil {
		panic(err)
	}
}
